<template>
  <el-form label-width="80px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="spuInfo.tmId">
        <el-option
          v-for="item in tmList"
          :key="item.id"
          :value="item.id"
          :label="item.tmName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="SPU描述"
        rows="4"
        v-model="spuInfo.description"
      />
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="(spuImageList as UploadUserFile[])"
        :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="预览图" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <template v-slot="{ row }">
        <el-select
          :placeholder="`未选择的${unUsedSalesAttrList.length}属性`"
          :style="{ marginRight: '10px' }"
          v-model="tempSaleAttr"
        >
          <el-option
            v-for="item in unUsedSalesAttrList"
            :value="`${item.id}:${item.name}`"
            :label="item.name"
          />
        </el-select>
        <el-button
          type="primary"
          size="default"
          @click="addSaleAttr"
          :disabled="!tempSaleAttr"
        >添加销售属性
        </el-button>
      </template>
    </el-form-item>
    <el-form-item>
      <el-table border stripe :data="spuSaleAttrList">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="属性名" prop="saleAttrName" />
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              :style="{marginRight: '10px'}"
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.isEdit"
              ref="editEle"
              v-model="row.inputValue"
              class="ml-1 w-20"
              size="small"
              @blur="handleInputConfirm(row, $event)"
              @keyup.enter="handleInputConfirm(row, $event)"
            />

            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="changeToEdit(row)"
            >
              + 添加属性
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作"></el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="spuSave">保存</el-button>
      <el-button type="default" size="default" @click="emit('setState', 2)"
      >取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm"
});
</script>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import useAttrStore from "@/stores/attr";
import type {
  baseSaleAttrListType,
  spuImageListType,
  spuInfoType,
  spuSaleAttrItemType,
  spuSaleAttrListType
} from "@/api/spu";
import {
  requestAllTrademarkList,
  type trademarkRecordsListType
} from "@/api/Trademark";
import {
  requestBaseSaleAttrList,
  requestSpuSaleAttrList,
  requestSpuImgList, requestSaveSpuInfo, requestUpdateSpuInfo
} from "@/api/spu";

//使用defineEmits拿到自定义事件
const emit = defineEmits<{
  (event: "setState", state: number): void;
}>();
//使用defineProps拿到传过来的spuInfo数据，将数据回填
const props = defineProps<{
  spuInfo: spuInfoType;
}>();

//实例化attr,拿到categoryId用于发送请求
const attrStore = useAttrStore();
//图片上传的前缀
const baseUrl = import.meta.env.VITE_API_URL;

// const fileList = ref<UploadUserFile[]>([
//   {
//     name: "food.jpeg",
//     url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
//   },
//   {
//     name: "plant-1.png",
//     url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
//   },
// ]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
/**
 * @tmList  品牌列表
 * @saleAttrList  销售属性列表
 * @spuImageList  spu图片列表
 * @spuSaleAttrList  销售属性值的列表
 * 根据新增还是修改去请求当前表单需要的数据，新增需要请求品牌和销售属性，修改需要请求品牌，销售属性，属性值，spu图片
 */
const tmList = ref<trademarkRecordsListType>([]);
const saleAttrList = ref<baseSaleAttrListType>([]);
const spuImageList = ref<spuImageListType>([]);
const spuSaleAttrList = ref<spuSaleAttrListType>([]);

const getAllUseData = async () => {
  //新增是没有id的，id是服务端添加的，通过判断是否存在id来判断是修改还是新增
  if (props.spuInfo.id) {
    //修改的时候4个请求
    const promise1 = requestAllTrademarkList();
    const promise2 = requestBaseSaleAttrList();
    const promise3 = requestSpuImgList(props.spuInfo.id);
    const promise4 = requestSpuSaleAttrList(props.spuInfo.id);
    try {
      //可以用直接接，也可以用一个变量保存一个个接
      [
        tmList.value,
        saleAttrList.value,
        spuImageList.value,
        spuSaleAttrList.value
      ] = await Promise.all([promise1, promise2, promise3, promise4]);
      //将请求回的图片名与路径添加到ele需要的属性上
      spuImageList.value.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      //添加一些临时属性
      spuSaleAttrList.value.forEach((item) => {
        item.isEdit = false; //读写
        item.inputValue = ""; //输入内容，数据绑定
      });
    } catch (e) {
      ElMessage.success("品牌请求或者属性列表请求失败");
    }
  } else {
    try {
      //新增的时候2个请求
      const result1 = await requestAllTrademarkList();
      const result2 = await requestBaseSaleAttrList();
      tmList.value = result1;
      saleAttrList.value = result2;
    } catch (e) {
      ElMessage.error("初始化失败");
    }
  }
};

/**@unUsedSalesAttrList 所有未选择的销售属性列表*/
const unUsedSalesAttrList = computed(() => {
  //所有销售属性多选框需要通过销售属性列表来展示
  return saleAttrList.value.filter((item1) => {
    return spuSaleAttrList.value.every((item2) => {
      return item2.saleAttrName !== item1.name;
    });
  });
});

onMounted(() => {
  getAllUseData();
});

/**@tempSaleAttr 创建一个临时的数据，用来展示已经选择的销售属性*/
const tempSaleAttr = ref("");
/**@addSaleAttr 添加销售属性的事件函数*/
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":");
  //创建一个临时的数据，用来添加新的销售属性
  const tempSpuSaleAttr = {
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  };
  //将数据插入到spuSaleAttrList
  spuSaleAttrList.value.push(tempSpuSaleAttr);
  //添加完成清空临时数据
  tempSaleAttr.value = "";
};

const changeToEdit = (row: spuSaleAttrItemType) => {
  row.isEdit = true;
  nextTick(() => {
    editEle.value?.focus();
  });
};

const editEle = ref<HTMLInputElement>();

const handleInputConfirm = (row: spuSaleAttrItemType, event: Event) => {
  let newInputValue = row.inputValue as string;
  if (!row.inputValue?.trim()) {
    return ElMessage.error("输入不能为空");
  }
  const isRepeat = row.spuSaleAttrValueList.some((item) => {
    return item.saleAttrValueName === newInputValue;
  });
  if (isRepeat) {
    return ElMessage.error("属性不能重复添加");
  }
  const newSaleAttrValue = {
    baseSaleAttrId: row.baseSaleAttrId as number,
    saleAttrValueName: newInputValue
  };
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  //最后清空并切换为按钮模式
  row.isEdit = false;
  row.inputValue = "";
};
//保存spu并整理数据发送请求
const spuSave = async () => {
  //收集需要发请求的图片列表
  const newSpuImageList = spuImageList.value.map(item => {
    return {
      imgUrl: item.response ? item.response.data : item.imgUrl,
      imgName: item.name
    };
  });
  //将请求不需要的属性删掉
  spuSaleAttrList.value.forEach(item => {
    delete item.isEdit;
    delete item.inputValue;
  });
  //将属性给到spuInfo
  props.spuInfo.spuSaleAttrList = spuSaleAttrList.value;
  props.spuInfo.spuImageList = newSpuImageList as spuImageListType;
  //通过判断id是否存在来确定是修改还是新增
  try {
    if (props.spuInfo.id) {
      await requestUpdateSpuInfo(props.spuInfo);
    } else {
      await requestSaveSpuInfo(props.spuInfo);
    }
  } catch (e) {
    ElMessage.error("新增或者更新数据失败");
  }
  //保存后，回到spu列表页
  emit("setState", 2);
};

</script>
